<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/9
 * Time: 17:32
 */

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\BrandModel;

class Brand extends Admin
{
    public function index()
    {
        $list = BrandModel::getList();
        $rows = [
            ['id', 'ID'],
            ['name', '品牌名称'],
            ['img', '缩略图','picture'],
            ['sort','排序','text.edit'],
            ['right_button','操作']
        ];
        return ZBuilder::make('table')
            ->setTableName('goods_brand')
            ->addColumns($rows)
            ->addTopButton('add')
            ->setRowList($list)
            ->addRightButtons('edit,delete')
            ->fetch();
    }

    public function add()
    {
        return ZBuilder::make('form')
            ->setPageTitle('添加品牌')
            ->setUrl(url('store'))
            ->isAjax(false)
            ->addFormItem('text','name','品牌名称')
            ->addImage('img','缩略图','建议上传80*80,大小小于100kb','0')
            ->addFormItem('text','sort','排序','',0)
            ->fetch();
    }

    public function edit($id = 0)
    {
        $data = BrandModel::getOne($id);
        return ZBuilder::make('form')
            ->setPageTitle('编辑品牌')
            ->setUrl(url('store'))
            ->isAjax(false)
            ->addHidden('id')
            ->addFormItem('text','name','品牌名称')
            ->addImage('img','缩略图','建议上传80*80,大小小于100kb','0')
            ->addFormItem('text','sort','排序','',0)
            ->setFormData($data)
            ->fetch();
    }

    public function store()
    {
        $data = input('post.');
        $id = input('param.id', 0);
        $this->nameExist($data['name'], $id);
        $validate = new \app\shop\validate\Brand();
        $check = $validate->check($data);
        if(!$check){
            $this->error($validate->getError());
        }
        $res = BrandModel::store($data, $id);
        if($res){
            $this->success('保存成功','index');
        }else{
            $this->error('保存失败');
        }
    }

    private function nameExist($name, $id)
    {
        $res = BrandModel::nameExist($name, $id);
        if($res){
            $this->error('品牌名称已存在');
        }
    }


}